import requests
from bs4 import BeautifulSoup
import json
import re


def get_insurance_law_json(url):
    """获取保险法JSON数据"""
    try:
        # 1. 发送HTTP请求
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Accept': 'application/json'
        }
        response = requests.get(url, headers=headers, timeout=10)
        response.encoding = 'utf-8'
        response.raise_for_status()

        # 2. 解析HTML
        soup = BeautifulSoup(response.text, 'html.parser')
        content = soup.find('font', id='Zoom') or soup.find('div', class_='article-content')

        if not content:
            return json.dumps({"error": "Content not found"}, ensure_ascii=False)

        # 3. 提取数据
        law_data = build_law_structure(content, url)

        # 4. 返回标准JSON
        return json.dumps(law_data, ensure_ascii=False, indent=2)

    except Exception as e:
        return json.dumps({"error": str(e)}, ensure_ascii=False)


def build_law_structure(content, url):
    """构建法律数据结构"""
    return {
        "metadata": get_metadata(content, url),
        "toc": get_toc(content),
        "chapters": get_chapters(content)
    }


def get_metadata(content, url):
    """获取元数据"""
    date_match = re.search(r'(\d{4})年(\d{1,2})月(\d{1,2})日', content.text)
    return {
        "title": "中华人民共和国保险法",
        "document_number": "主席令第十一号",
        "publish_date": f"{date_match.group(1)}-{date_match.group(2).zfill(2)}-{date_match.group(3).zfill(2)}" if date_match else None,
        "effective_date": "2009-10-01",
        "source_url": url,
        "source_website": "中国政府网"
    }


def get_toc(content):
    """获取目录"""
    toc = []
    # 修正：使用string参数替代text
    toc_heading = content.find(string=re.compile(r'目\s*录'))
    if toc_heading:
        toc_p = toc_heading.find_next('p')
        if toc_p:
            for item in toc_p.stripped_strings:
                if '章' in item or '节' in item:
                    toc.append(item.strip())
    return toc


def get_chapters(content):
    """获取所有章节"""
    chapters = {}
    current_chapter = ""
    current_section = ""

    for element in content.find_all(['p', 'strong']):
        text = element.get_text().strip()

        # 处理章节
        chapter_match = re.match(r'第[一二三四五六七八九十]+章\s+(.*)', text)
        if chapter_match:
            current_chapter = chapter_match.group(1)
            chapters[current_chapter] = {
                "type": "chapter",
                "sections": {},
                "articles": []
            }
            current_section = ""
            continue

        # 处理节
        section_match = re.match(r'第[一二三四五六七八九十]+节\s+(.*)', text)
        if section_match:
            current_section = section_match.group(1)
            chapters[current_chapter]["sections"][current_section] = {
                "type": "section",
                "articles": []
            }
            continue

        # 处理条款
        article_match = re.match(r'第([一二三四五六七八九十百]+)条\s+(.*)', text)
        if article_match:
            article = build_article(article_match)

            if current_section:
                chapters[current_chapter]["sections"][current_section]["articles"].append(article)
            else:
                chapters[current_chapter]["articles"].append(article)

    return chapters


def build_article(match):
    """构建条款数据结构"""
    return {
        "article_number": match.group(1),
        "article_number_arabic": chinese_to_arabic(match.group(1)),
        "content": clean_text(match.group(2)),
        "type": "article"
    }


def clean_text(text):
    """清理文本"""
    text = re.sub(r'\s+', ' ', text)
    text = re.sub(r'[\u3000\xa0]', ' ', text)
    return text.strip()


def chinese_to_arabic(chinese_num):
    """中文数字转阿拉伯数字"""
    num_map = {
        '零': 0, '一': 1, '二': 2, '三': 3, '四': 4,
        '五': 5, '六': 6, '七': 7, '八': 8, '九': 9,
        '十': 10, '百': 100
    }
    try:
        return sum(num_map[char] for char in chinese_num if char in num_map)
    except:
        return None

get_insurance_law_data=(get_insurance_law_json('https://www.gov.cn/flfg/2009-02/28/content_1246444.htm'))

